<script setup lang="ts">
import {ref, watch, nextTick} from 'vue'
import {debounce} from "lodash-es";

const isLoading = ref(true)
const isView = ref(false)
const fastPanelBox = ref<HTMLElement | null>(null)
const value = ref('')
const valueTranslate = ref({
    loading: true,
    word: '',
    result: '',
    error: '',
})
const web = ref<HTMLElement | null>(null)
const translate = debounce((value) => {
    valueTranslate.value.loading = true
    valueTranslate.value.error = ''
    valueTranslate.value.word = ''
    valueTranslate.value.result = ''
    fetch('https://focusany.com/api/plugin/Translate/trans', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({word: value}),
    })
        .then(response => response.json())
        .then(ret => {
            if (ret.code === 0) {
                valueTranslate.value.word = ret.data['word']
                valueTranslate.value.result = ret.data['explain']
            } else {
                valueTranslate.value.error = ret.msg
            }
        })
        .catch((error) => {
            console.error('translate.error', error)
            valueTranslate.value.error = '查询出现错误'
        })
        .finally(() => {
            valueTranslate.value.loading = false
            nextTick(() => {
                const height = fastPanelBox.value?.clientHeight
                focusany.view.setHeight(height || 100)
            })
        })
}, 500)
watch(value, (value) => {
    translate(value)
})

const tabs = [
    {
        name: 'Dict海词',
        url: 'https://dict.cn/search?q={query}',
    },
    {
        name: '有道词典',
        url: 'https://dict.youdao.com/search?q={query}',
    },
    {
        name: '百度翻译',
        url: 'https://fanyi.baidu.com/#en/zh/{query}',
    },
    {
        name: '必应翻译',
        url: 'https://cn.bing.com/translator?text={query}&from=&to=zh-Hans',
    },
    {
        name: '金山词霸',
        url: 'http://www.iciba.com/{query}',
    },
]
const tab = ref(tabs[0].name)

const webUrl = ref('')
const setWebUrl = debounce(async (url) => {
    if (!web.value) {
        return
    }
    // @ts-ignore
    await web.value.stop()
    // @ts-ignore
    await web.value.loadURL(url)
    webUrl.value = url
}, 500)

watch([tab, value], () => {
    const urlTemplate = tabs.find(item => item.name === tab.value)?.url
    if (!urlTemplate || !value.value) {
        setWebUrl('')
    } else {
        setWebUrl(urlTemplate.replace('{query}', value.value))
    }
})

// mock
if (0 && !window.focusany) {
    let callback: any = null
    window.focusany = {
        onPluginReady: (cb) => {
            callback = cb
        },
        // @ts-ignore
        getQuery: (requestId: string) => {
            return {keywords: 'hello'}
        },
        // @ts-ignore
        setSubInput: (cb, title, isView, isTranslate) => {
            console.log('setSubInput', title, isView, isTranslate)
        },
    }
    setTimeout(() => {
        callback({
            actionName: 'keyword',
            requestId: '1',
            keywords: 'hello',
            isView: true,
        })
    }, 1000)
}

focusany.onPluginReady((data) => {
    console.log('onPluginReady', data, navigator.userAgent)
    if (['keyword', 'view'].includes(data.actionName)) {
        const query = focusany.getQuery(data.requestId)
        console.log('onPluginReady.query', query)
        if (query.keywords) {
            value.value = query.keywords
        } else if (query.currentText) {
            value.value = query.currentText
        }
    }
    if (!data['isView']) {
        focusany.setSubInput((data) => {
            value.value = data
        }, '输入查询', true, false)
    }
    isView.value = !!data['isView']
    isLoading.value = false
})
</script>

<template>
    <div :class="isView?'':'border-t border-solid border-gray-300'"
         style="height:100vh;">
        <div v-if="isLoading" class="flex h-full">
            <div class="m-auto">
                <a-spin/>
            </div>
        </div>
        <div v-else-if="isView" class="p-2"
             ref="fastPanelBox">
            <div v-if="valueTranslate.loading"
                 class="rounded-lg p-2 text-center">
                正在查询...
            </div>
            <div v-else-if="valueTranslate.error"
                 class="text-red-500 bg-red-50 rounded-lg p-2 text-center">
                <div v-if="valueTranslate.error==='WordNotFound'">单词不存在</div>
                <div v-else>{{ valueTranslate.error }}</div>
            </div>
            <div v-else>
                <div class="font-bold text-lg">
                    <icon-book/>
                    {{ valueTranslate.word }}
                </div>
                <div>{{ valueTranslate.result }}</div>
            </div>
        </div>
        <div v-else class="flex flex-col h-full">
            <div class="p-2 border-bottom border-gray-300 border-solid flex">
                <div class="flex-grow">
                    <a-input v-model="value" size="large" placeholder="输入搜索">
                        <template #prepend>
                            <icon-search/>
                        </template>
                    </a-input>
                </div>
                <div class="pl-3">
                    <a-button v-for="item in tabs"
                              :key="item.name"
                              size="large"
                              @click="tab=item.name"
                              :type="tab===item.name?'primary':undefined">
                        {{ item.name }}
                    </a-button>
                </div>
            </div>
            <div class="flex-grow relative">
                <webview class="h-full"
                         ref="web"
                         allowpopups
                         sandbox
                         src="about:blank"
                ></webview>
                <div v-if="!webUrl" class="absolute inset-0 flex">
                    <a-empty class="m-auto" description="请输入内容查询"/>
                </div>
            </div>
        </div>
    </div>
</template>
